package Pattern.ObserverPattern.program5;

import java.util.ArrayList;
import java.util.List;

public class Test5 {
    public static void main(String[] args) {
        Subject subject = new EmailTopic("DAY DAY UP");
        Observer observer = new EmailTopicSubscriber("Yang");
        Observer observer1 = new EmailTopicSubscriber("Li");
        observer.setSubject(subject);
        observer1.setSubject(subject);
        subject.register(observer);
        subject.register(observer1);
        subject.notifyObservers();
    }
}

interface Observer {
    void update();

    void setSubject(Subject subject);
}

interface Subject {
    void register(Observer observer);

    void unregister(Observer observer);

    void notifyObservers();

    String getUpdate(Observer observer);
}

class EmailTopicSubscriber implements Observer {
    private String name;
    private Subject subject;

    public EmailTopicSubscriber(String name) {
        this.name = name;
    }

    @Override
    public void update() {
        String message = subject.getUpdate(this);
        if (message == null) {
            System.out.println(name + ": No new messages");
        } else {
            System.out.println(name + " Retrieving message: " + message);
        }
    }

    @Override
    public void setSubject(Subject subject) {
        this.subject = subject;
    }

}

class EmailTopic implements Subject {
    private final List<Observer> observers = new ArrayList<Observer>();
    private String message;

    public EmailTopic() {
    }

    public EmailTopic(String message) {
        this.message = message;
    }

    @Override
    public void register(Observer observer) {
        if (!observers.contains(observer)) {
            observers.add(observer);
        }
    }

    @Override
    public void unregister(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        observers.forEach(Observer::update);
    }

    @Override
    public String getUpdate(Observer observer) {
        return this.message;
    }

    public void postMessage(String s) {
        System.out.println("Message posted to my topic: " + message);
        this.message = message;
        notifyObservers();
    }
}

